package com.example.vote.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.vote.entity.TpRecord;
import com.example.vote.mapper.TpRecordMapper;
import com.example.vote.service.BizException;
import com.example.vote.service.ITpRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 * 投票系统-投票记录表-6 服务实现类
 * </p>
 *
 * @author 廖老师
 * @since 2023-12-04
 */
@Service
public class TpRecordServiceImpl extends ServiceImpl<TpRecordMapper, TpRecord> implements ITpRecordService {

    @Resource
    TpRecordMapper recordMapper;

    @Override
    @Transactional(noRollbackFor = BizException.class)
    public void commit(int vid, int[] iids, Map<String, Object> loginedUser)
            throws BizException {
        // 判断登录
        if (loginedUser == null) {
            throw new BizException("请先登录系统!");
        }
        // 判断是否已经投票
        LambdaQueryWrapper<TpRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TpRecord::getVid, vid);
        lqw.eq(TpRecord::getUsid, loginedUser.get("id"));
        final Long count = recordMapper.selectCount(lqw);
        if (count > 0) {
            throw new BizException("您已经投过票了!");
        }
        // 判断选项
        if (iids == null || iids.length == 0) {
            throw new BizException("请选择选项!");
        }
        // 保存数据库
        TpRecord tr = new TpRecord();
        int usid = Integer.parseInt("" + loginedUser.get("id"));
        for (int iid : iids) {
            tr.setId(null);
            tr.setIid(iid);
            tr.setVid(vid);
            tr.setUsid(usid);
            recordMapper.insert(tr);
        }
    }
}
